import router from '@/router'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import store from './store'
import { asyncRoutes } from '@/router'

const whiteList = [
  '/login',
  '/404'
]

// 前置守卫
router.beforeEach(async(to, from, next) => {
  nprogress.start()

  if (store.getters.token) {
    // 存在 token
    if (to.path === '/login') {
      // 中转到主页
      next('/')
      nprogress.done()
    } else {
      // 是否获取过用户信息
      if (!store.getters.userId) {
        const { roles } = await store.dispatch('user/getUserInfo')
        // 筛选后的路由
        const filterRoutes = asyncRoutes.filter(item => {
          return roles.menus.includes(item.name)
        })
        store.commit('user/setRoutes', filterRoutes)
        router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }])
        next(to.path)
      } else {
        next()
      }
    }
  } else {
    // 没有 token
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      nprogress.done()
    }
  }
})

// 后置守卫
router.afterEach(() => {
  nprogress.done()
})
